#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <vector>
#include <sstream>

using namespace std;

class FileTransferClient
{
	private:
	int sd,len;
	struct sockaddr_in address;
	public:
	bool Connect(string IP, unsigned long int API);
	bool ls(vector<string> &filelist);
	bool getfile(string &file);
};

bool FileTransferClient::Connect(string IP, unsigned long int API)
{
	int res;
	sd=socket(AF_INET,SOCK_STREAM,0);
	address.sin_family=AF_INET;
	address.sin_port=htons(API);
	address.sin_addr.s_addr=inet_addr(IP.c_str());
	len=sizeof(address);
	res=connect(sd,(struct sockaddr*)&address,len);
	if(res==-1)
	{
		perror("error\n");
		return 0;
	}
}

bool FileTransferClient::ls(vector<string> &filelist)
{
	cout<<"lsing"<<endl;
	int length=0;
	int position=0,last=0;
	string cmd="command:ls";
	char *buf=(char*)malloc(20);
	write(sd,cmd.c_str(),cmd.length());
	int i=0;
	length=read(sd,buf,16);
	//cout<<buf<<endl;
	buf[16]='\0';
	string len(buf);
	len=len.substr(4,15);
	cout<<len<<endl;
	int mem;
	stringstream ss(len);
	ss>>mem;
	cout<<mem<<endl;
	char * buffer=(char *)malloc(mem);
	length=read(sd,buffer,mem);
	string menu(buffer);
	//cout<<buffer<<endl;
	position=menu.find("\r\n");
	while(position!=menu.npos)
	{
		string temp=menu.substr(last,position-last);
		filelist.push_back(temp);
		//cout<<"position"<<position<<"  last:"<<last<<endl;
		cout<<temp<<endl;
		last=position+2;
		//cout<<"last:"<<last<<endl;
		position=menu.find("\r\n",last);
	}
	return true;	
}
	
bool FileTransferClient::getfile(string &file)
{
	FILE *fp;
	fp=fopen("./FileServer.cpp","w");
	int length;
	char *buf=(char*)malloc(20);
	string cmd="command:get "+file+"\r\n";
	cout<<cmd<<cmd.length()<<endl;
	write(sd,cmd.c_str(),cmd.length());
	read(sd,buf,16);
	string len(buf);
	len=len.substr(4,15);
	cout<<len<<endl;
	int mem;
	stringstream ss(len);
	ss>>mem;
	cout<<mem<<endl;
	char * buffer=(char *)malloc(1010);
	int i=0;
	while(i<mem)
	{
		length=read(sd,buffer,1000);
		cout<<length<<endl;
		fwrite(buffer,1,length,fp);
		i+=length;
	}
	//cout<<buffer<<endl;
	//cout<<length<<endl;
	fclose(fp);
	return true;
}
		
int main()
{
	string cmd;
	int num=1;
	cout<<"you can list the files by using the command ls"<<endl;
	cin>>cmd;
	FileTransferClient ftc;
	vector<string> VT;
	string IP;
	IP="192.168.3.7";
	ftc.Connect(IP.c_str(),0x6400);
	if(cmd=="ls")
	{	
		ftc.ls(VT);
	}
	cout<<VT.size()<<endl;
	for(vector<string>::iterator it=VT.begin();it!=VT.end();it++)
	{
		cout<<num<<". "<<(*it)<<endl;
		num++;
	}
	while(1)
	{	
		cout<<"you can type in the number of file that you want to transfer"<<endl;
		cin>>num;
		if(num==-1) break;
		ftc.getfile(VT[num-1]);
	}
	return 0;
}
